package com.uparlange.project.flextris
{
	import flash.events.Event;
	import flash.geom.Point;
	
	import mx.core.IVisualElement;
	
	import spark.components.Group;

	/**
	 * Represents a Piece part
	 * 
	 * @author Ugo Parlange
	 */ 
	public class PiecePart extends Group
	{
		/**
		 * Main graphic element to display
		 */ 
		public var visualElement : IVisualElement;
		
		/**
		 * Piece part position
		 */ 
		public var position : Point;
		
		/**
		 * Constructor
		 */ 
		public function PiecePart() {
			super();
			init()
		}
		
		/**
		 * Move the piece part bottom if space available
		 * 
		 * @param aMatrice Matrice, the matrice's constraint
		 */ 
		public function moveBottom(aMatrice : Matrice) : void {
			var nextPoint : Point = new Point(position.x, position.y + 1);
			if(aMatrice.isFree(nextPoint)) {
				// move position
				position.y += 1;
				// refresh position
				refresh();
			}
		}
		
		/**
		 * Called to update position
		 */ 
		public function refresh(aWidth:Number=-1, aHeight:Number=-1) : void {
			if(numElements == 0) {
				addElement(visualElement);
			}
			if(aWidth != -1) {
				visualElement.width = aWidth;
			}
			if(aHeight != -1) {
				visualElement.height = aHeight;
			}
			visualElement.x = position.x * visualElement.width;
			visualElement.y = position.y * visualElement.height;
		}
		
		/**
		 * Initialize PiecePart
		 */
		private function init() : void {
			addEventListener(Event.ADDED, addedEventHandler);
		}
		
		/**
		 * Called when piece part added on stage
		 */ 
		private function addedEventHandler(anEvent:Event) : void {
			removeEventListener(Event.ADDED, addedEventHandler);
			refresh();
		}
	}
}